package org.jflame.web;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;

import org.jflame.commons.csv.CsvAccessException;
import org.jflame.commons.csv.CsvWriter;
import org.jflame.commons.excel.ExcelAccessException;
import org.jflame.commons.excel.ExcelCreator;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

public abstract class ExcelUtils {

    /**
     * 实体数据生成excel文件,并输出到HttpServletResponse下载流
     * 
     * @param data
     * @param fileName 文件名,浏览器要显示的文件名
     * @param response HttpServletResponse
     * @throws IOException
     */
    public static <T> void exportExcel(final Collection<T> data, final String dataGroup, final String fileName,
            HttpServletResponse response) throws ExcelAccessException, IOException {
        response.reset();
        WebUtils.setFileDownloadHeader(response, fileName, null);
        ServletOutputStream out = response.getOutputStream();
        ExcelCreator.export(data, dataGroup, out, false);
    }

    public static <T> void exportExcel(final Collection<T> data, final String fileName, HttpServletResponse response)
            throws ExcelAccessException, IOException {
        exportExcel(data, null, fileName, response);
    }

    /**
     * 实体数据生成csv文件,并输出到HttpServletResponse 下载流
     * 
     * @param data 数据集合
     * @param fileName 下载文件名
     * @param response HttpServletResponse
     * @throws CsvAccessException
     * @throws IOException
     */
    public static <T> void exportCsv(final Collection<T> data, final String fileName, HttpServletResponse response)
            throws CsvAccessException, IOException {
        exportCsv(data, null, fileName, response);
    }

    /**
     * 实体数据生成csv文件,并输出到HttpServletResponse 下载流
     * 
     * @param data 数据集合
     * @param dataGroup 分组
     * @param fileName 下载文件名
     * @param response HttpServletResponse
     * @throws CsvAccessException
     * @throws IOException
     */
    public static <T> void exportCsv(final Collection<T> data, final String dataGroup, final String fileName,
            HttpServletResponse response) throws CsvAccessException, IOException {
        response.reset();
        File tmpPath = Files.createTempFile(fileName, "csv")
                .toFile();
        try (CsvWriter csvWriter = new CsvWriter(tmpPath)) {
            csvWriter.writeEntityData(data, dataGroup);
            WebUtils.setFileDownloadHeader(response, fileName, tmpPath.length());
            ServletOutputStream out = response.getOutputStream();
            Files.copy(tmpPath.toPath(), out);
            out.flush();
        } finally {
            tmpPath.delete();
        }
    }

}
